import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import defaultSettings from "@/settings";
import theme from '@/utils/theme.js'
NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/bind', '/register','/forgotPassword','/loginTwo']
const title = defaultSettings.title || "网络报修";
function getPageTitle2(pageTitle) {
  if (pageTitle) {
    return `${pageTitle} - ${title}`;
  }
  return `${title}`;
}

router.beforeEach((to, from, next) => {
  if (navigator.userAgent.match(/mobile/i)) {
    window.location.href="/mobile"
  }else{
  NProgress.start()
  // 设置页面标题
  document.title = getPageTitle2(to.meta.title);
  if (getToken()) {
  //  to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/login'||to.path === '/loginTwo') {
      next({ path: '/' })
      NProgress.done()
    } else {
        if (store.state.permission.menus.length ==0) {
          store.dispatch('permission/receptionRoutes').then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          }).catch(err => {
            store.dispatch('user/LogOut').then(() => {
              Message.error(err)
              next({ path: '/' })
            })
          })
          theme.renderingTheme(store.state.baseSettings.theme)
        } else {
          next()
        }
      }
    } else {
      // 没有token
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单，直接进入
        next()
      } else {
       //next(`/login`) // 否则全部重定向到登录页
        let url = process.env.NODE_ENV === 'production'?`/login?redirect=${to.fullPath}`:`/loginTwo`
        next(url);
        NProgress.done()
      }
    }
  }
  // if( from.path == to.path ){
  //   // 不要跳转了
  //   console.log('提示: 已经在个路径里了')
  // }else{
  //
  // }
})

router.afterEach(() => {
  NProgress.done()
})
